﻿Imports System.Globalization
Imports System.IO

Partial Public Class Sum_Tariff_Not_Pay
    Inherits System.Web.UI.Page

    Dim clsGet As New ClassFunctionGetData
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim lbPage As Label = CType(Master.FindControl("lbPage"), Label)
            lbPage.Text = "SUM MATERIAL FREE "
            ViewState("Sum") = CreateDataTable()
            txtDate.Text = Date.Now.AddDays(-14).ToString("dd MMM yyyy", New CultureInfo("en-US"))
            txtDateTo.Text = Date.Now.AddDays(14).ToString("dd MMM yyyy", New CultureInfo("en-US"))
        End If
    End Sub

    Private Sub LoadData()
        Dim agent As String = ""
        If (RadioTYpePay.SelectedValue = "C") Then
            agent = txtAgent.Text
        Else
            agent = ""
        End If
        Dim dt As DataTable = clsGet.Get_Booking_For_MAT_FREE_REPORT(radioDestination.SelectedValue, CDate(txtDate.Text).ToString("yyyyMMdd"), CDate(txtDateTo.Text).ToString("yyyyMMdd"), radioPORT.SelectedValue, agent)
        If (dt.Rows.Count > 0) Then
            Dim Booking_no As String = ""
            For Each dr As DataRow In dt.Rows
                If (dr.Item("Booking_no") & "" <> "") Then
                    Dim dtMat As DataTable = clsGet.Get_Booking_For_MAT_FREE_REPORT_Item(dr.Item("Booking_no"))
                    'Dim dtWharf As DataTable = clsGet.Get_BookingWharf(dr.Item("Booking_no"))
                    'Dim Shifting As Boolean = False
                    'Dim BookingShifting As String = ""
                    'If (dtWharf.Rows.Count > 0) Then
                    '    If (dtWharf.Rows(0).Item("Shift_Booking") & "" <> "") Then
                    '        Shifting = True
                    '        BookingShifting = dtWharf.Rows(0).Item("Shift_Booking")
                    '    End If
                    'End If

                    If (dtMat.Rows.Count > 0) Then
                        Dim _184 As Boolean = True
                        Dim _200 As Boolean = True
                        Dim _001 As Boolean = True
                        Dim _268 As Boolean = True
                        Dim _236 As Boolean = True
                        Dim _237 As Boolean = True
                        Dim _100 As Boolean = True
                        Dim _255 As Boolean = True
                        For Each dx As DataRow In dtMat.Rows
                            If dx.Item("MATERIAL") & "" = "000000002100000184" Then
                                _184 = False
                            End If
                            If dx.Item("MATERIAL") & "" = "000000002100000200" Then
                                _200 = False
                            End If
                            If dx.Item("MATERIAL") & "" = "000000002100000001" Then
                                _001 = False
                            End If
                            If dx.Item("MATERIAL") & "" = "000000002100000236" Then
                                _236 = False
                                _237 = False
                            ElseIf dx.Item("MATERIAL") & "" = "000000002100000237" Then
                                _237 = False
                            End If
                            If (dr.Item("PORT") = "L") Then
                                If dx.Item("MATERIAL") & "" = "000000002100000281" Then
                                    _268 = False
                                End If
                            Else
                                If dx.Item("MATERIAL") & "" = "000000002100000268" Then
                                    _268 = False
                                End If
                                If dx.Item("MATERIAL") & "" = "000000002100000255" Then
                                    _255 = False
                                End If
                            End If
                            If (dx.Item("MATERIAL") & "" = "000000002100000100") Or (dx.Item("MATERIAL") & "" = "000000002100000099") Or (dx.Item("MATERIAL") & "" = "000000002100000098") Or (dx.Item("MATERIAL") & "" = "000000002100000097") Then
                                _100 = False
                            End If
                        Next
                        If ((_184) Or (_200) Or (_001) Or (_268) Or (_236)) Then
                            If (RadioTYpePay.SelectedValue = "A") Then
                                AddData(dr.Item("Booking_no"), dr.Item("Vehicle_Text"), dr.Item("Vehicle_GRT"), dr.Item("Vehicle_DWT"), dr.Item("Vehicle_LOA"), dr.Item("Vehicle_Draft"), dr.Item("PORT"), dr.Item("MAgent_no"), _184, _200, _001, _268, _236, _237, _255, _100)
                            Else
                                AddData(dr.Item("Booking_no"), dr.Item("Vehicle_Text"), dr.Item("Vehicle_GRT"), dr.Item("Vehicle_DWT"), dr.Item("Vehicle_LOA"), dr.Item("Vehicle_Draft"), dr.Item("PORT"), dr.Item("MAgent_no"), Not (_184), Not (_200), Not (_001), Not (_268), Not (_236), Not (_237), Not (_255), Not (_100))
                            End If
                        Else
                            If (RadioTYpePay.SelectedValue = "C") Then
                                If (dr.Item("PORT") = "L") Then
                                    AddData(dr.Item("Booking_no"), dr.Item("Vehicle_Text"), dr.Item("Vehicle_GRT"), dr.Item("Vehicle_DWT"), dr.Item("Vehicle_LOA"), dr.Item("Vehicle_Draft"), dr.Item("PORT"), dr.Item("MAgent_no"), True, True, True, True, True, True, False, False)
                                Else
                                    AddData(dr.Item("Booking_no"), dr.Item("Vehicle_Text"), dr.Item("Vehicle_GRT"), dr.Item("Vehicle_DWT"), dr.Item("Vehicle_LOA"), dr.Item("Vehicle_Draft"), dr.Item("PORT"), dr.Item("MAgent_no"), True, True, True, True, True, True, True, True)
                                End If

                            End If
                        End If
                    Else
                        If (RadioTYpePay.SelectedValue = "A") Then
                            If (dr.Item("PORT") = "L") Then
                                AddData(dr.Item("Booking_no"), dr.Item("Vehicle_Text"), dr.Item("Vehicle_GRT"), dr.Item("Vehicle_DWT"), dr.Item("Vehicle_LOA"), dr.Item("Vehicle_Draft"), dr.Item("PORT"), dr.Item("MAgent_no"), True, True, True, True, True, True, False, False)
                            Else
                                AddData(dr.Item("Booking_no"), dr.Item("Vehicle_Text"), dr.Item("Vehicle_GRT"), dr.Item("Vehicle_DWT"), dr.Item("Vehicle_LOA"), dr.Item("Vehicle_Draft"), dr.Item("PORT"), dr.Item("MAgent_no"), True, True, True, True, True, True, True, True)
                            End If

                        End If
                    End If

                End If
            Next
            dt = ViewState("Sum")
            If (dt.Rows.Count > 0) Then
                gridItem.DataSource = ViewState("Sum")
                gridItem.DataBind()
                rowType.Visible = True
                rowPrint.Visible = True
            Else
                gridItem.DataSource = Nothing
                gridItem.DataBind()
                rowType.Visible = False
                rowPrint.Visible = False
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูล ');", True)
            End If

        Else
            gridItem.DataSource = Nothing
            gridItem.DataBind()
            rowType.Visible = False
            rowPrint.Visible = False
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูล ');", True)
        End If

    End Sub

    Private Sub AddData(ByVal booking_no As String, ByVal Vehicle_Text As String, ByVal GRT As String, ByVal DWT As String, ByVal LOA As String, ByVal Draft As String, ByVal PORT As String, ByVal Customer As String, ByVal _184 As Boolean, ByVal _200 As Boolean, ByVal _001 As Boolean, ByVal _268 As Boolean, ByVal _236 As Boolean, ByVal _237 As Boolean, ByVal _255 As Boolean, ByVal _100 As Boolean)
        Dim dt As DataTable = ViewState("Sum")
        Dim dr As DataRow = dt.NewRow
        Dim product_Amount As Double = 0.0
        Dim Product_Load As String = ""
        Dim Product_Disch As String = ""
        Dim Product_Bulk As Double = 0.0
        Dim L_D As String = ""
        dr.Item("Booking_no") = booking_no
        dr.Item("Vehicle_Text") = Vehicle_Text
        Dim dtProduct As DataTable = clsGet.Get_Booking_Product(booking_no)
        If (dtProduct.Rows.Count > 0) Then
            L_D = dtProduct.Rows(0).Item("Product_Event") & ""
        End If
        dtProduct = clsGet.Get_Load_Unload_Product(booking_no, "")
        For Each dm As DataRow In dtProduct.Rows
            If (L_D = "L") Then
                If Product_Load = "" Then
                    Product_Load = dm.Item("Product_name")
                Else
                    Product_Load &= "," & dm.Item("Product_name")
                End If
            Else
                If Product_Disch = "" Then
                    Product_Disch = dm.Item("Product_name")
                Else
                    Product_Disch &= "," & dm.Item("Product_name")
                End If
            End If
            Try
                If (PORT = "L") Then
                    product_Amount += CDbl(dm.Item("LU_BLMT"))
                Else
                    If (dm.Item("BU_Truck") & "" = "") Then
                        product_Amount += CDbl(dm.Item("BU_Bill"))
                    Else
                        product_Amount += CDbl(dm.Item("BU_Truck"))
                    End If
                    If (dm.Item("BU_Bill") & "" = "") Then
                        Product_Bulk += dm.Item("BU_Manifest")
                    Else
                        Product_Bulk += dm.Item("BU_Bill")
                    End If
                End If

            Catch ex As Exception

            End Try

        Next
        dr.Item("Product_Load") = Product_Load
        dr.Item("Product_Disch") = Product_Disch
        If (PORT = "L") Then
            dr.Item("Product_Amount") = product_Amount
        Else
            dr.Item("Product_Amount") = Product_Bulk
            product_Amount = Product_Bulk
        End If


        Dim dtActual As DataTable = clsGet.GetActualTIme(booking_no)
        Dim dtLog_Out As DataTable = clsGet.Get_Booking_LogSheet_Out(booking_no)

        Dim Berthing_Date As String = dtActual.Rows(0).Item("Berthing_Date")
        If (Berthing_Date.Trim().Length < 9) Then
            Try
                Dim days As String = Berthing_Date.Substring(0, 2)
                Dim Month As String = GetNameMonth(Berthing_Date.Substring(3, 2))
                Dim Year As String = "20" & Berthing_Date.Substring(6, 2)
                Berthing_Date = days & " " & Month & " " & Year
            Catch ex As Exception

            End Try
        End If
        Dim Depart_Actual_Date As String = dtLog_Out.Rows(0).Item("Last_Date")
        If (Depart_Actual_Date.Trim().Length < 9) Then
            Try
                Dim days As String = Depart_Actual_Date.Substring(0, 2)
                Dim Month As String = GetNameMonth(Depart_Actual_Date.Substring(3, 2))
                Dim Year As String = "20" & Depart_Actual_Date.Substring(6, 2)
                Depart_Actual_Date = days & " " & Month & " " & Year
            Catch ex As Exception

            End Try
        End If

        Dim ts = DateDiff("n", Berthing_Date & " " & dtActual.Rows(0).Item("Berthing_TimeFrom"), Depart_Actual_Date & " " & dtLog_Out.Rows(0).Item("Last_Time")) ' in case you need it in minutes

        Dim StandartTIme As Double = (ts / 60).ToString("###################.00")
        Try
            If (CInt(StandartTIme.ToString.Split(".")(1)) > 49) Then
                StandartTIme = CDbl(StandartTIme.ToString.Split(".")(0)) + 1
            ElseIf (CInt(StandartTIme.ToString.Split(".")(1)) > 0) Then
                StandartTIme = CDbl(StandartTIme.ToString.Split(".")(0)) + 0.5
            End If
            dr.Item("Hr") = StandartTIme
        Catch ex As Exception

        End Try


        dr.Item("Berth") = Berthing_Date
        dr.Item("Depart") = Depart_Actual_Date
        If (_184) Then
            dr.Item("_184") = ComputeMoney("000000002100000184", GRT, LOA, DWT, Draft, product_Amount, Customer, PORT, StandartTIme, "")
        Else
            dr.Item("_184") = ""
        End If
        If (_200) Then
            dr.Item("_200") = ComputeMoney("000000002100000200", GRT, LOA, DWT, Draft, product_Amount, Customer, PORT, StandartTIme, "")
        Else
            dr.Item("_200") = ""
        End If
        If (_001) Then
            dr.Item("_001") = ComputeMoney("000000002100000001", GRT, LOA, DWT, Draft, product_Amount, Customer, PORT, StandartTIme, "")
        Else
            dr.Item("_001") = ""
        End If
        If (_255) Then
            dr.Item("_255") = ComputeMoney("000000002100000255", GRT, LOA, DWT, Draft, product_Amount, Customer, PORT, StandartTIme, "")
        Else
            dr.Item("_255") = ""
        End If
        If (_100) Then
            Dim dtTruck As DataTable = clsGet.Get_Load_Unload_Product_Bulk(booking_no, "", "")
            Dim Truck6 As Integer = 0
            Dim Truck810 As Integer = 0
            Dim Trailer As Integer = 0
            Dim Trailer2 As Integer = 0
            Dim CTtruck As Boolean = True
            Dim Admis As Double = 0
            For Each da As DataRow In dtTruck.Rows
                Truck6 += CInt(da.Item("_Truck6"))
                Truck810 += CInt(da.Item("_Truck810"))
                Trailer += CInt(da.Item("_Trailer"))
                Trailer2 += CInt(da.Item("_Trailer2"))
            Next
            If (Truck6 > 0) Then
                Admis += CDbl(ComputeMoney("000000002100000099", GRT, LOA, DWT, Draft, product_Amount, Customer, PORT, StandartTIme, Truck6))
            End If
            If (Truck810 > 0) Then
                Admis += CDbl(ComputeMoney("000000002100000100", GRT, LOA, DWT, Draft, product_Amount, Customer, PORT, StandartTIme, Truck810))
            End If
            If (Trailer > 0) Then
                Admis += CDbl(ComputeMoney("000000002100000099", GRT, LOA, DWT, Draft, product_Amount, Customer, PORT, StandartTIme, Trailer))
            End If
            If (Trailer2 > 0) Then
                Admis += CDbl(ComputeMoney("000000002100000098", GRT, LOA, DWT, Draft, product_Amount, Customer, PORT, StandartTIme, Trailer2))
            End If
            dr.Item("_100") = Admis
        End If


        Dim dtTug As DataTable = clsGet.Get_Booking_LogSheet_Tug(booking_no, "", "W")
        Dim Tug As Integer = 0
        Dim Boat As Integer = 0
        Dim chkTug As Boolean = False
        For Each drTug As DataRow In dtTug.Rows
            If (drTug.Item("Tug_Name") & "" <> "") Then
                Dim dttugType As DataTable = clsGet.Get_TugBoat(drTug.Item("Tug_Name"))
                If (dttugType.Rows.Count > 0) Then
                    chkTug = True
                    If (dttugType.Rows(0).Item("Tug_Type") & "" = "0") Then
                        Tug += 1
                    Else
                        If (drTug.Item("Tug_Event") & "" = "W") Then
                            Boat += 1
                        Else
                            Tug += 1
                        End If
                    End If
                End If


            End If
        Next
        If (chkTug) Then
            If (_236) And (Tug > 0) Then
                dr.Item("_236") = ComputeMoney("000000002100000236", GRT, LOA, DWT, Draft, product_Amount, Customer, PORT, StandartTIme, Tug)
            ElseIf (_237) And (Boat > 0) Then
                dr.Item("_236") = ComputeMoney("000000002100000237", GRT, LOA, DWT, Draft, product_Amount, Customer, PORT, StandartTIme, Boat)
            Else
                dr.Item("_236") = ""
            End If
        Else
            dr.Item("_236") = ""
        End If

        If (PORT = "L") Then
            If (_268) Then
                dr.Item("_268") = ComputeMoney("000000002100000281", GRT, LOA, DWT, Draft, product_Amount, Customer, PORT, StandartTIme, "")
            Else
                dr.Item("_268") = ""
            End If
        Else
            If (_268) Then
                dr.Item("_268") = ComputeMoney("000000002100000268", GRT, LOA, DWT, Draft, product_Amount, Customer, PORT, StandartTIme, "")
            Else
                dr.Item("_268") = ""
            End If
        End If
        Dim Sum As Double = 0.0
        Try
            Sum += CDbl(dr.Item("_184"))
        Catch ex As Exception

        End Try
        Try
            Sum += CDbl(dr.Item("_200"))
        Catch ex As Exception

        End Try
        Try
            Sum += CDbl(dr.Item("_001"))
        Catch ex As Exception

        End Try
        Try
            Sum += CDbl(dr.Item("_236"))
        Catch ex As Exception

        End Try
        Try
            Sum += CDbl(dr.Item("_268"))
        Catch ex As Exception

        End Try
        dr.Item("_Sum") = Sum
        Dim dtw As DataTable = clsGet.Get_BookingWharf(booking_no)
        Dim WHarf As String = ""
        For Each dw As DataRow In dtw.Rows
            If WHarf = "" Then
                WHarf = dw.Item("Wharf")
            Else
                WHarf &= "," & dw.Item("Wharf")
            End If
        Next
        dr.Item("Wharf") = WHarf
        If (Sum <> 0.0) Then
            dt.Rows.Add(dr)
            dt.AcceptChanges()
            ViewState("Sum") = dt
        End If

    End Sub

    Private Function CreateDataTable() As DataTable
        Dim dt As New DataTable
        dt.Columns.Add("Booking_no", GetType(String))
        dt.Columns.Add("Vehicle_Text", GetType(String))
        dt.Columns.Add("Product_Load", GetType(String))
        dt.Columns.Add("Product_Disch", GetType(String))
        dt.Columns.Add("Product_Amount", GetType(String))
        dt.Columns.Add("Hr", GetType(String))
        dt.Columns.Add("_184", GetType(String))
        dt.Columns.Add("_200", GetType(String))
        dt.Columns.Add("_001", GetType(String))
        dt.Columns.Add("_268", GetType(String))
        dt.Columns.Add("_236", GetType(String))
        dt.Columns.Add("_255", GetType(String))
        dt.Columns.Add("_100", GetType(String))
        dt.Columns.Add("_Sum", GetType(String))
        dt.Columns.Add("Berth", GetType(String))
        dt.Columns.Add("Depart", GetType(String))
        dt.Columns.Add("Wharf", GetType(String))
        dt.AcceptChanges()
        Return dt
    End Function

    Public Sub Paginate(ByVal sender As Object, ByVal e As CommandEventArgs)
        ViewState("Booking_OLD") = ""
        Dim CurrentIndex As Integer = gridItem.PageIndex
        Select Case e.CommandArgument.ToString().ToLower()
            Case "first"
                gridItem.PageIndex = 0
            Case "prev"
                If (gridItem.PageIndex <> 0) Then
                    gridItem.PageIndex = CurrentIndex - 1
                End If
            Case "next"
                If (gridItem.PageIndex <> gridItem.PageCount) Then
                    gridItem.PageIndex = CurrentIndex + 1
                End If
            Case "last"
                gridItem.PageIndex = gridItem.PageCount
        End Select
        gridItem.DataSource = ViewState("Sum")
        gridItem.DataBind()
    End Sub

    Protected Sub ddlPage_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
        ViewState("Booking_OLD") = ""
        Dim Page As GridViewRow = gridItem.BottomPagerRow
        Dim ddlPage As DropDownList = CType(Page.Cells(0).FindControl("ddlPage"), DropDownList)
        gridItem.PageIndex = ddlPage.SelectedIndex
        gridItem.DataSource = ViewState("Sum")
        gridItem.DataBind()
    End Sub

    Private Sub gridItem_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridItem.RowDataBound
        If (e.Row.RowType = DataControlRowType.DataRow) Then
            Dim Sum As Double = 0.0
            Try
                e.Row.Cells(7).Text = FormatNumber(e.Row.Cells(7).Text, 2)
            Catch ex As Exception

            End Try
            Try
                e.Row.Cells(9).Text = FormatNumber(e.Row.Cells(9).Text, 2)
            Catch ex As Exception

            End Try
            Try
                e.Row.Cells(10).Text = FormatNumber(e.Row.Cells(10).Text, 2)
            Catch ex As Exception

            End Try
            Try
                e.Row.Cells(11).Text = FormatNumber(e.Row.Cells(11).Text, 2)
            Catch ex As Exception

            End Try
            Try
                e.Row.Cells(12).Text = FormatNumber(e.Row.Cells(12).Text, 2)
            Catch ex As Exception

            End Try
            Try
                e.Row.Cells(13).Text = FormatNumber(e.Row.Cells(13).Text, 2)
            Catch ex As Exception

            End Try
            Try
                e.Row.Cells(14).Text = FormatNumber(e.Row.Cells(14).Text, 2)
            Catch ex As Exception

            End Try
            Try
                e.Row.Cells(15).Text = FormatNumber(e.Row.Cells(15).Text, 2)
            Catch ex As Exception

            End Try
            Try
                e.Row.Cells(16).Text = FormatNumber(e.Row.Cells(16).Text, 2)
            Catch ex As Exception

            End Try
        ElseIf (e.Row.RowType = DataControlRowType.Pager) Then
            Dim Page As GridViewRow = gridItem.BottomPagerRow
            Dim ddlPage As DropDownList = CType(e.Row.FindControl("ddlPage"), DropDownList)
            Dim lblPageCount As Label = CType(e.Row.FindControl("lbPageCount"), Label)
            If Not (ddlPage Is Nothing) Then
                For i As Integer = 0 To gridItem.PageCount - 1
                    Dim intPageNumber As Integer = i + 1
                    Dim IsItem As New ListItem(intPageNumber.ToString())
                    If (i = gridItem.PageIndex) Then
                        IsItem.Selected = True
                    End If
                    ddlPage.Items.Add(IsItem)
                Next
            End If
            If Not (lblPageCount Is Nothing) Then
                lblPageCount.Text = gridItem.PageCount.ToString()
            End If
        End If
    End Sub

    Private Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        Dim dt As DataTable = ViewState("Sum")
        If Not (dt Is Nothing) Then
            dt.Rows.Clear()
        End If
        LoadData()
    End Sub

    Public Function CreateDataset() As DataSet
        Dim ds As New DataSet
        Dim dt As New DataTable
        ds.Tables.Add(dt)
        dt.Columns.Add("id", GetType(String))
        dt.Columns.Add("MAT_NAME", GetType(String))
        dt.Columns.Add("name", GetType(String))
        dt.Columns.Add("data1", GetType(String))
        dt.Columns.Add("data2", GetType(String))
        dt.Columns.Add("data3", GetType(String))
        dt.Columns.Add("data4", GetType(String))
        ds.Tables(0).AcceptChanges()
        ds.AcceptChanges()
        Return ds
    End Function

    Private Function ComputeMoney(ByVal MATERIAL As String, ByVal GRT As String, ByVal LOA As String, ByVal DWT As String, ByVal Draft As String, ByVal ProductValue As String, ByVal Customer_no As String, ByVal PORT As String, ByVal _StandardTime As String, ByVal Valuexx As String)
        Dim dtRelation As DataTable = clsGet.Get_MeterailRelation(MATERIAL)
        Dim ds As New DataSet
        ds = CreateDataset()
        If (dtRelation.Rows.Count > 0) Then
            Dim Value As Double = 0.0
            Select Case dtRelation.Rows(0).Item("Relation")
                Case "01" 'สูตรคำนวนน้ำหนักเรือ GRT 
                    Value = GRT
                Case "02" 'L.O.A.
                    Value = LOA
                Case "03" 'DWT
                    Value = DWT
                Case "04" 'Draft
                    Value = Draft
                Case "05" 'Product
                    Value = ProductValue
                Case "06"
                    Value = 0.0
            End Select
            Dim conditioncheck As Boolean = True
            For Each drR As DataRow In dtRelation.Rows

                If (conditioncheck) Then
                    'ทำการเปรียบเทียบช่วงน่ำหนักเรือ
                    If (drR.Item("Compute_Between") & "" = "A") Then
                        'แบบแรกตกช่วงคิด
                        If ((CDbl(drR("Point_Start")) <= Value) And (CDbl(drR("Point_End")) >= Value)) Then
                            'Rate ตกในช่วง
                            Dim rate As String = drR.Item("Mat_Rate")
                            If (dtRelation.Rows(0).Item("Customer_no") & "" <> "") Then
                                Dim Cus() As String = dtRelation.Rows(0).Item("Customer_no").ToString().Split(",")
                                For i As Integer = 0 To Cus.Length - 1
                                    If (Cus(i).ToString = Customer_no) Then
                                        rate = dtRelation.Rows(0).Item("Customer_Rate").ToString().Split(",")(i)
                                        Exit For
                                    End If
                                Next
                            End If
                            Dim drNew As DataRow = ds.Tables(0).NewRow()
                            drNew.Item("id") = CInt(drR.Item("Meterial")).ToString()
                            drNew.Item("name") = drR.Item("Mat_Name")
                            drNew.Item("MAT_NAME") = ""  'ไม่ได้แสดง
                            If (CInt(Value).ToString() = "0") Then
                                If (dtRelation.Rows(0).Item("Relation") & "" <> "05") Then
                                    Value = 1.0
                                End If
                                drNew.Item("data1") = ""
                            Else
                                drNew.Item("data1") = Value
                            End If
                            Try
                                drNew.Item("data2") = rate
                                Dim newValue As Double = 0
                                If (drR.Item("Point_Unit") = "0") Then
                                    newValue = 1
                                Else
                                    newValue = (Value / CDbl(drR.Item("Point_Unit")))
                                End If
                                Dim StardardTime As Double = 0
                                If (drR("data3") = "S") Or (drR("data3") = "C") Then
                                    StardardTime = CDbl(_StandardTime)
                                End If
                                If (drR("Data3") = "N") Then
                                    drNew.Item("data3") = ""
                                    drNew.Item("data4") = (newValue * CDbl(rate)).ToString("###############0.00")
                                ElseIf (drR("Data3") = "S") Then
                                    Session("Lay_Time") = StardardTime
                                    drNew.Item("data3") = StardardTime
                                    drNew.Item("data4") = ((newValue * CDbl(rate)) * StardardTime).ToString("###############0.00")
                                Else
                                    If (drR.Item("Compute_Count") & "" = "") Then
                                        If (drR.Item("Compute_C") & "" = "D") Then
                                            If (StardardTime = 0) Then
                                                drNew.Item("data3") = 1
                                            Else
                                                drNew.Item("data3") = ((CDbl(StardardTime) \ 24) + 1).ToString()
                                            End If

                                        Else
                                            If (Value Mod CDbl(drR.Item("Point_Unit"))) <> 0 Then
                                                drNew.Item("data3") = (CInt(Value \ CDbl(drR.Item("Point_Unit"))) + 1).ToString()
                                            Else
                                                drNew.Item("data3") = CInt(Value \ CDbl(drR.Item("Point_Unit"))).ToString()
                                            End If
                                        End If
                                    Else
                                        If (Valuexx = "") Then
                                            drNew.Item("data3") = drR.Item("Compute_Count")
                                        Else
                                            drNew.Item("data3") = Valuexx
                                        End If

                                    End If

                                    drNew.Item("data4") = (CDbl(rate) * CDbl(drNew.Item("data3"))).ToString("###############0.00")
                                End If
                                If (drR.Item("LowRate") & "" = "") Then
                                    drR.Item("LowRate") = "0"
                                End If
                                If (CDbl(drR.Item("LowRate")) > 0.0) Then
                                    If (CDbl(drR.Item("LowRate")) > CDbl(drNew.Item("data4"))) Then
                                        'ราคาต่ำกว่า ราคาขั้นต่ำ
                                        If (drNew.Item("data3") = "") Then
                                            drNew.Item("data2") = drR.Item("LowRate")
                                            drNew.Item("data4") = drR.Item("LowRate")
                                        Else
                                            drNew.Item("data4") = drR.Item("LowRate")
                                            drNew.Item("data2") = CDbl(drR.Item("LowRate") / drNew.Item("data3")).ToString("################0.00")
                                        End If
                                    End If
                                End If
                            Catch ex As Exception
                                '((LOA-5)*Draft)+10%
                                If (drR.Item("LowRate") & "" = "") Then
                                    drR.Item("LowRate") = "0"
                                End If
                                Dim LoACompute As Double = ((LOA - 5.0) * Draft) + ((((LOA - 5.0) * Draft) * 10) / 100).ToString("##################0.00")
                                If (CDbl(drR.Item("LowRate")) > LoACompute) Then
                                    drNew.Item("data2") = drR.Item("LowRate")
                                    drNew.Item("data3") = "1"
                                    drNew.Item("data4") = drR.Item("LowRate")
                                Else
                                    drNew.Item("data2") = LoACompute.ToString()
                                    drNew.Item("data3") = "1"
                                    drNew.Item("data4") = LoACompute.ToString()
                                End If
                            End Try
                            ds.Tables(0).Rows.Add(drNew)
                            ds.Tables(0).AcceptChanges()
                            Exit For
                        End If
                    Else
                        'แบบสองผ่านช่วงไหนคิดหมด
                        If ((CDbl(drR("Point_Start")) <= Value)) Then
                            'Rate ตกในช่วง
                            Dim drNew As DataRow = ds.Tables(0).NewRow()
                            drNew.Item("id") = CInt(drR.Item("Meterial")).ToString()
                            drNew.Item("name") = drR.Item("Mat_Name")
                            drNew.Item("MAT_NAME") = "" 'ไม่ม่ชื่อ
                            Dim Nvalue As Double = 0
                            If (Value > drR("Point_End")) Then
                                Nvalue = drR("Point_End") - CDbl(drR("Point_Start"))
                            Else
                                Nvalue = Value - CDbl(drR("Point_Start"))
                            End If
                            Dim rate As String = drR.Item("Mat_Rate")
                            If (dtRelation.Rows(0).Item("Customer_no") & "" <> "") Then
                                Dim Cus() As String = dtRelation.Rows(0).Item("Customer_no").ToString().Split(",")
                                For i As Integer = 0 To Cus.Length - 1
                                    If (Cus(i).ToString = Customer_no) Then
                                        rate = dtRelation.Rows(0).Item("Customer_Rate").ToString().Split(",")(i)
                                        Exit For
                                    End If
                                Next
                            End If
                            drNew.Item("data1") = Nvalue
                            drNew.Item("data2") = rate

                            Dim newValue As Double = 0
                            If (drR.Item("Point_Unit") = "0") Then
                                newValue = 1
                            Else
                                newValue = (Nvalue / CDbl(drR.Item("Point_Unit")))
                            End If
                            Dim StardardTime As Double = 0
                            If (drR("data3") = "S") Or (drR("data3") = "C") Then
                                StardardTime = _StandardTime
                            End If
                            If (drR("Data3") = "N") Then
                                drNew.Item("data3") = ""
                                drNew.Item("data4") = (newValue * CDbl(rate)).ToString("###############0.00")

                            ElseIf (drR("Data3") = "S") Then
                                'ทำการคำนวณหา Stardard Time
                                'If (StardardTime = 0) Then
                                '    StardardTime = 1
                                'End If
                                Session("Lay_Time") = StardardTime
                                drNew.Item("data3") = StardardTime
                                drNew.Item("data4") = ((newValue * CDbl(rate)) * StardardTime).ToString("###############0.00")
                            Else
                                If (drR.Item("Compute_Count") & "" = "") Then
                                    If (drR.Item("Compute_C") & "" = "D") Then
                                        drNew.Item("data3") = (CDbl(StardardTime) \ 24).ToString()
                                    Else
                                        If (Value Mod CDbl(drR.Item("Point_Unit"))) <> 0 Then
                                            drNew.Item("data3") = (CInt(Value \ CDbl(drR.Item("Point_Unit"))) + 1).ToString()
                                        Else
                                            drNew.Item("data3") = CInt(Value \ CDbl(drR.Item("Point_Unit"))).ToString()
                                        End If
                                    End If
                                Else
                                    drNew.Item("data3") = drR.Item("Compute_Count")
                                End If

                                drNew.Item("data4") = (CDbl(rate) * CDbl(drNew.Item("data3"))).ToString("###############0.00")
                            End If
                            If (drR.Item("LowRate") & "" = "") Then
                                drR.Item("LowRate") = "0"
                            End If
                            If (CDbl(drR.Item("LowRate")) > 0.0) Then
                                If (CDbl(drR.Item("LowRate")) > CDbl(drNew.Item("data4"))) Then
                                    'ราคาต่ำกว่า ราคาขั้นต่ำ
                                    If (drNew.Item("data3") = "") Then
                                        drNew.Item("data2") = drR.Item("LowRate")
                                        drNew.Item("data4") = drR.Item("LowRate")
                                    Else
                                        drNew.Item("data4") = drR.Item("LowRate")
                                        drNew.Item("data2") = CDbl(drR.Item("LowRate") / drNew.Item("data3")).ToString("################0.00")
                                    End If
                                End If
                            End If

                            ds.Tables(0).Rows.Add(drNew)
                            ds.Tables(0).AcceptChanges()
                            Exit For
                        End If
                    End If
                End If
            Next
        Else
            'ไม่พบข้อมูลการผูกสูตร
            Dim Plant As String = "1104"
            If (PORT = "L") Then
                Plant = "1103"
            End If
            dtRelation = clsGet.Get_SubMeterail(MATERIAL)
            If (dtRelation.Rows.Count > 0) Then
                For Each dm As DataRow In dtRelation.Rows
                    If (Plant = dm.Item("WERKS")) Then
                        Dim drNew As DataRow = ds.Tables(0).NewRow()
                        Dim id As String = ""
                        Try
                            id = CInt(MATERIAL).ToString()
                        Catch ex As Exception
                            id = MATERIAL
                        End Try
                        drNew.Item("id") = id
                        drNew.Item("name") = ""
                        drNew.Item("MAT_NAME") = ""
                        drNew.Item("data1") = ""
                        drNew.Item("data2") = dm.Item("KBETR")
                        drNew.Item("data3") = "1"


                        drNew.Item("data4") = CDbl(dm.Item("KBETR") * CDbl("1")).ToString("###############0.00")
                        ds.Tables(0).Rows.Add(drNew)
                        ds.Tables(0).AcceptChanges()
                    End If
                Next
            End If
        End If
        Try
            Return ds.Tables(0).Rows(0).Item("data4")
        Catch ex As Exception
            Return "0"
        End Try

    End Function

    Private Function GetNameMonth(ByVal Month As String) As String
        Try
            Select Case (CInt(Month).ToString("00"))
                Case "01"
                    Return "Jan"
                Case "02"
                    Return "Feb"
                Case "03"
                    Return "Mar"
                Case "04"
                    Return "Apr"
                Case "05"
                    Return "May"
                Case "06"
                    Return "Jun"
                Case "07"
                    Return "Jul"
                Case "08"
                    Return "Aug"
                Case "09"
                    Return "Sep"
                Case "10"
                    Return "Oct"
                Case "11"
                    Return "Nov"
                Case "12"
                    Return "Dec"
                Case Else
                    Return ""
            End Select
        Catch ex As Exception
            Return Month
        End Try

    End Function

    Private Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrint.Click
        Dim service As New _ReportingService.Report

        Dim optWindow As String = "left=0,top=0,location=no,menubar=no,resizable=yes,scrollbars=yes,status=yes,toolbar=no"
        Dim Orientation As Boolean = True
        Dim ReportName As String = String.Empty
        Dim reportDataSource As String = String.Empty
        Dim paraName As String = String.Empty
        Dim paraValue As String = String.Empty
        Dim reportType As String = String.Empty
        Dim urlDisplay As String = String.Empty
        Dim dsReport As New DataSet
        Dim dt As DataTable = ViewState("Sum")
        Try
            For Each dr As DataRow In dt.Rows
                Try
                    dr.Item("Product_Amount") = FormatNumber(dr.Item("Product_Amount"), 2)
                Catch ex As Exception

                End Try
                Try
                    dr.Item("_184") = FormatNumber(dr.Item("_184"), 2)
                Catch ex As Exception

                End Try
                Try
                    dr.Item("_200") = FormatNumber(dr.Item("_200"), 2)
                Catch ex As Exception

                End Try
                Try
                    dr.Item("_001") = FormatNumber(dr.Item("_001"), 2)
                Catch ex As Exception

                End Try
                Try

                    dr.Item("_268") = FormatNumber(dr.Item("_268"), 2)
                Catch ex As Exception

                End Try
                Try
                    dr.Item("_236") = FormatNumber(dr.Item("_236"), 2)
                Catch ex As Exception

                End Try
                Try
                    dr.Item("_255") = FormatNumber(dr.Item("_255"), 2)
                Catch ex As Exception

                End Try
                Try
                    dr.Item("_100") = FormatNumber(dr.Item("_100"), 2)
                Catch ex As Exception

                End Try
                Try
                    dr.Item("_Sum") = FormatNumber(dr.Item("_Sum"), 2)
                Catch ex As Exception

                End Try
                dt.AcceptChanges()
            Next
        Catch ex As Exception

        End Try
        dsReport.Tables.Add(ViewState("Sum"))
        dsReport.AcceptChanges()
        ReportName = "Free_Tariff.rdlc"
        ' dsReport = New DataSet
        reportDataSource = "Free_Tariff_Free_Tariff"
        paraName = "DateTimeNow"
        paraValue = DateTime.Now.ToString()
        Orientation = False
        reportType = radioType.SelectedValue

        urlDisplay = service.CreateReporting(dsReport, reportDataSource, reportType, ReportName, paraName, paraValue, Orientation, "")

        Dim oldFile As String = String.Empty
        oldFile = Server.MapPath(urlDisplay)
        Dim fileInfo As FileInfo = New FileInfo(oldFile)
        Dim reportPath As String = "../WriteReport/"

        Dim newFileName As String = DateTime.Now.ToString("_yyMMdd_HHmmss", New CultureInfo("en-US"))
        newFileName = "Sum_Material_Free_Report" & newFileName

        If fileInfo.Exists Then
            fileInfo.MoveTo(fileInfo.DirectoryName & "/" & newFileName & fileInfo.Extension)
            urlDisplay = reportPath & newFileName & fileInfo.Extension
        End If

        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "window.open('" + urlDisplay + "','_blank','" + optWindow + "');", True)
    End Sub
    Private Sub MainPage_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
        Dim ds As DataSet = Session("UserData")
        If Not (ds Is Nothing) Then
            Page.MasterPageFile = clsGet.GetMaster_Page(ds.Tables(0).Rows(0).Item("User_Name").ToString(), "M")
        End If
    End Sub

    Private Sub radioPORT_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles radioPORT.SelectedIndexChanged
        If (radioPORT.SelectedValue = "L") Then
            rowDestination.Visible = True
        Else
            rowDestination.Visible = False
        End If
    End Sub

    Private Sub RadioTYpePay_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RadioTYpePay.SelectedIndexChanged
        If (RadioTYpePay.SelectedValue = "C") Then
            rowAgent.Visible = True
        Else
            rowAgent.Visible = False
        End If
    End Sub
End Class